﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using qkview.Models;
using WebMatrix.WebData;

namespace qkview.Controllers
{
    [Authorize] 
    public class ApiSectionController : ApiController
    {
        private QKVEntities db = new QKVEntities();

        // GET api/ApiSection
        public IEnumerable<Section> GetSections()
        {
            var sections = db.Sections.Include(s => s.Note);
            return sections.AsEnumerable();
        }

        // GET api/ApiSection/5
        public Section GetSection(int id)
        {
            Section section = db.Sections.Find(id);
            if (section == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return section;
        }

/// <summary>
/// Not used anywhere
/// </summary>
/// <param name="id"></param>
/// <param name="section"></param>
/// <returns></returns>
        public HttpResponseMessage PutSection(int id, Section section)
        {
            //if (!ModelState.IsValid)
            //{
            //    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            //}

            //if (id != section.SectionID)
            //{
            //    return Request.CreateResponse(HttpStatusCode.BadRequest);
            //}

            //db.Entry(section).State = EntityState.Modified;

            //try
            //{
            //    db.SaveChanges();
            //}
            //catch (DbUpdateConcurrencyException ex)
            //{
            //    return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            //}

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // POST api/ApiSection
        public HttpResponseMessage PostSection(SectionDto sectionDto)
        {
            Section section = sectionDto.ToEntity();
            var board =db.Boards.FirstOrDefault(x => x.Notes.Any(y => y.NoteID == section.NoteID));
            if (board.UserID  != WebSecurity.CurrentUserId)
            {
                return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Permission denied");
            }
            UserSetting us = db.UserSettings.FirstOrDefault(x => x.UserProfile.UserName == User.Identity.Name);
            int allowedSections = us.TotalSection;
            if (db.Sections.Count(x => x.NoteID == section.NoteID) >= allowedSections)
            {
                ModelState.AddModelError("", "Please upgrade your account to create more Sections.");
            }          
            if (ModelState.IsValid)
            {

                db.Sections.Add(section);
                db.SaveChanges();
                sectionDto.SectionID =Common.Encode(section.SectionID.ToString());
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, sectionDto);
                //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = section.SectionID }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // DELETE api/ApiSection/5
        public HttpResponseMessage DeleteSection(string id)
        {
            Section section = db.Sections.Find(Convert.ToInt32(Common.Decode(id)));
            if (section == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            var board = db.Boards.FirstOrDefault(x => x.Notes.Any(y => y.NoteID == section.NoteID));
            
            if (board.UserID != WebSecurity.CurrentUserId)
            {
                return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Permission denied");
            }
            db.Sections.Remove(section);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}